#include "global.h"
#include "parse.h"
#include "tool.h"
#include "code.h"

Bool DEBUG = FALSE;
Bool ERRORED = FALSE;
Bool QUIET = FALSE;

FILE *source = NULL;
FILE *error = NULL;
FILE *dbgout = NULL;
FILE *asmout = NULL;

int error_count = 0;
int warning_count = 0;

void print_usage()
{
    printf("Usage: xc0_compile sourceFile [-o asmFile] [-e errorFile] [-d debugFile]\n");
    printf("       Specify -q option to enable quiet mode.\n");
    printf("       -h option to display this help info.\n");
    exit(0);
}

int main(int argc, char **argv)
{
    int i;

    error = stderr;
    dbgout = stdout;
    asmout = stdout;

    if (argc == 1) {
        print_usage();
    }
    if (argc >= 2) {
        if (strcmp(argv[1], "-h") == 0) {
            print_usage();
        }
        source = fopen(argv[1], "r");
        if (source == NULL) {
            fprintf(stderr, "Open source file failed. Please check it again.\n");
            print_usage();
        }
    }
    for (i = 1; i < argc - 1; i++) {
        if (strcmp(argv[i], "-h") == 0 || strcmp(argv[argc - 1], "-h") == 0) {
            print_usage();
        }
        else if (strcmp(argv[i], "-o") == 0) {
            asmout = fopen(argv[i + 1], "w");
            if (asmout == NULL) {
                fprintf(stderr, "Open output file failed. Please check it again.\n");
                print_usage();
            }
        }
        else if (strcmp(argv[i], "-d") == 0) {
            dbgout = fopen(argv[i + 1], "w");
            if (dbgout == NULL) {
                fprintf(stderr, "Open debug file failed. Please check it again.\n");
                print_usage();
            }
        }
        else if (strcmp(argv[i], "-e") == 0) {
            error = fopen(argv[i + 1], "w");
            if (error == NULL) {
                fprintf(stderr, "Open error info output file failed. Please check it again.\n");
                print_usage();
            }
        }
        else if (QUIET == FALSE && (strcmp(argv[i], "-q") == 0 || strcmp(argv[argc - 1], "-q") == 0)) {
            QUIET = TRUE;
            fprintf(stdout, "Quiet mode enabled. No error info will be present.\n");
        }
    }
    parse();
    fprintf(error, "%d errors, %d warnings.\n", error_count, warning_count);
    print_normal_table();
    print_func_table();
    print_midcode_table();
    gen_assembly_code();

    fclose(source);
    fclose(error);
    fclose(dbgout);
    fclose(asmout);
	return 0;
}

// gcc -Wall -g global.h la.h la.c parse.h parse.c util.h util.c error.c error.h table.h table.c main.c
// gedit global.h la.h la.c parse.h parse.c util.h util.c error.c error.h table.h table.c main.c
// svn commit ./XC0_37060222 -m ""

// .test file.
// 1-9.test files is correct source files.
// 10-14.test files are files with error.